package com.plian.system.service.sys.user;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.alibaba.excel.write.metadata.fill.FillWrapper;
import com.alibaba.fastjson.JSONObject;
import com.plian.Tools.*;
import com.plian.Tools.pagedata.PageData;
import com.plian.spring.SpringUtil;
import com.plian.system.bean.sys.UserExcelBean;
import com.plian.system.bean.wf.User;
import com.plian.system.cache.UserCache;
import com.plian.system.config.RedisUtils;
import com.plian.system.config.exception.MyRuntimeException;
import com.plian.system.constant.sys.BaseConstant;
import com.plian.system.dao.sys.fun.PerGroupDao;
import com.plian.system.dao.sys.orgzation.OrgzationDao;
import com.plian.system.dao.sys.orgzation.UserGroupRelationDao;
import com.plian.system.dao.sys.orgzation.WorkFlowGroupDao;
import com.plian.system.dao.sys.per.PerUserOrgDao;
import com.plian.system.dao.sys.per.UserOrgDao;
import com.plian.system.dao.sys.user.UserDao;
import com.plian.system.entity.sys.Loginfo;
import com.plian.system.entity.sys.Office;
import com.plian.system.enumeratea.LogStatusEnum;
import com.plian.system.helper.wf.SessionHelper;
import com.plian.system.mapper.im.BaseInvestmentExecutionMapper;
import com.plian.system.mapper.sys.LoginfoMapper;
import com.plian.system.model.CommonCode;
import com.plian.system.model.ListResult;
import com.plian.system.model.ObjResult;
import com.plian.system.model.page.Page;
import com.plian.system.service.fr.bulletin.BulletinService;
import com.plian.system.service.sys.office.IOfficeService;
import com.plian.system.service.sys.orgzation.IOrgService;
import com.plian.system.service.sys.orgzation.OrgzationService;
import com.plian.system.service.sys.per.PerUserService;
import com.plian.system.service.sys.token.TokenService;
import com.plian.system.vo.sys.UserReviewInfoVO;
import com.plian.system.vo.sys.UserRoleInfoVO;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.core.env.Environment;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.InputStream;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 用户操作
 */
@Service
public class UserService {
    @Autowired
    UserDao userDao;
    @Autowired
    TokenService tokenService;
    @Autowired
    UserOrgDao userOrgDao;
    @Autowired
    OrgzationDao orgzationDao;
    @Autowired
    private Environment environment;
    @Autowired
    PerUserService perUserService;
    @Autowired
    PerUserOrgDao perUserOrgDao;
    @Autowired
    BulletinService bulletinService;
    @Autowired
    private UserGroupRelationDao userGroupRelationDao;
    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private WorkFlowGroupDao workFlowGroupDao;
    @Autowired
    private PerGroupDao perGroupDao;
    @Resource
    private BaseInvestmentExecutionMapper baseInvestmentExecutionMapper;

    @Autowired
    private OrgzationService orgzationService;

    @Autowired
    private IOrgService orgService;

    @Autowired
    private IOfficeService officeService;

    @Autowired
    private LoginfoMapper loginfoMapper;

    /**
     * 用于
     */
    private static final String userLoginErrNum = "userLoginErrNum";

    private static final long loginErrNumTime = 60 * 60;

    private static final long threeMonthTime = 3L*30L*24L*60L*60L*1000L;


    /**
     * logger属性.
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(UserService.class);

    /**
     * 保存
     *
     * @param p
     * @throws Exception
     */
    public ObjResult save(PageData p) {
        String userName = p.getString("username");
        String passWord = p.getString("password");
        PageData p1 = new PageData();
        ObjResult objResult;
        try {
            p1 = userDao.getUser(userName);
            if (p1 != null) {
                objResult = new ObjResult(CommonCode.FAIL);
                objResult.setMessage("用户名已存在!");
            } else {
//                String ecpassword = new SimpleHash("SHA-1", userName, passWord).toString();    //密码加密
                if (Tools.isEmpty(p.getString("type"))) {
                    p.put("type", "3");
                } else {
                    String type = p.getString("type");
                    if (!"0".equals(type) && !"1".equals(type) && !"2".equals(type) && !"3".equals(type)) {
                        objResult = new ObjResult(CommonCode.VALIDATE);
                        objResult.setMessage("类型错误!");
                        return objResult;
                    }
                }

                if (Tools.isEmpty(p.getString("isGroupAdmin"))) {
                    p.put("isGroupAdmin", "0");
                }
                p.put("creatUser", TokenUtil.getTokenUserId());
                p.put("creatDate", new Date());
                p.put("password", passWord);
                p.put("id", UuidUtil.get32UUID());
                p.put("isInitialPassword", 2);
                p.put("passwordUpdateTime", new Date());
                if (StringUtil.isNotBlank(p.getString("phone"))){
                    p.put("phone", EncryptUtil.encryptBase64(p.getString("phone"), BaseConstant.BASE64_KEY));
                }
                userDao.save(p);
                UserCache.update(p.getString("id"));
                objResult = new ObjResult(CommonCode.SUCCESS);
            }
        } catch (Exception e) {
            LOGGER.error(ExceptionUtils.getStackTrace(e));
            objResult = new ObjResult(CommonCode.ERROR);
        }
        return objResult;
    }


    /**
     * 集团创建账号
     *
     * @param p
     * @throws Exception
     */
    @Transactional(rollbackFor = RuntimeException.class)
    public ObjResult saveGroup(PageData p) {
        String userName = p.getString("username");
        String passWord = p.getString("password");
        PageData p1 = new PageData();
        ObjResult objResult;
        try {
            p1 = userDao.getUser(userName);
            if (p1 != null) {
                objResult = new ObjResult(CommonCode.FAIL);
                objResult.setMessage("用户名已存在!");
            } else {
//                String ecpassword = new SimpleHash("SHA-1", userName, passWord).toString();    //密码加密
                if (Tools.isEmpty(p.getString("type"))) {
                    p.put("type", "3");
                } else {
                    String type = p.getString("type");
                    if (!"0".equals(type) && !"1".equals(type) && !"2".equals(type) && !"3".equals(type)) {
                        objResult = new ObjResult(CommonCode.VALIDATE);
                        objResult.setMessage("类型错误!");
                        return objResult;
                    }
                }

                if (Tools.isEmpty(p.getString("isGroupAdmin"))) {
                    p.put("isGroupAdmin", "0");
                }
                String userId = UuidUtil.get32UUID();
                p.put("creatUser", TokenUtil.getTokenUserId());
                p.put("creatDate", new Date());
                p.put("password", passWord);
                p.put("passwordUpdateTime", new Date());
                if (StringUtil.isNotBlank(p.getString("phone"))){
                    p.put("phone", EncryptUtil.encryptBase64(p.getString("phone"), BaseConstant.BASE64_KEY));
                }
                p.put("id", userId);
                userDao.save(p);
                UserCache.update(p.getString("id"));

                //保存账号-单位权限
                //需要保存的单位
                List<String> orgIds = new ArrayList<>();
                //前端传来旳集合
                List<HashMap<String, Object>> list = (List<HashMap<String, Object>>) p.get("list");

                //岗位集合
                List<PageData> postList = new ArrayList<>();
                //拿到单位id
                for (HashMap<String, Object> stringObjectHashMap : list) {
                    orgIds.add(stringObjectHashMap.get("orgId").toString());
                    List<HashMap<String, Object>> list1 = (List<HashMap<String, Object>>) stringObjectHashMap.get("postList");
                    if (list1 != null && list1.size() > 0) {
                        for (HashMap<String, Object> objectHashMap : list1) {
                            PageData params = new PageData();
                            params.put("id", userId);
                            PageData pageData = new PageData();
                            pageData.put("id", UuidUtil.get32UUID());
                            pageData.put("userId", userId);
                            pageData.put("userName", userName);
                            pageData.put("groupId", objectHashMap.get("groupId").toString());
                            pageData.put("groupName", objectHashMap.get("groupName").toString());
                            pageData.put("organizationId", stringObjectHashMap.get("orgId").toString());
                            postList.add(pageData);
                        }
                    }

                }
                userGroupRelationDao.deleteByUserId(userId);
                if (postList != null && postList.size() > 0) {
                    PageData pageData = new PageData();
                    pageData.put("pageDataList", postList);
                    userGroupRelationDao.insertBatch(pageData);
                }


                //拿到单位-账号集合
                List<PageData> groupIds = saveUserOrg(p.getString("id"), orgIds);
                for (HashMap<String, Object> stringObjectHashMap : list) {
                    for (PageData p2 : groupIds) {
                        if (stringObjectHashMap.get("orgId").toString().equals(p2.getString("orgId"))) {
                            stringObjectHashMap.put("userOrgId", p2.getString("id"));
                        }
                    }
                }
                PageData pd = new PageData();
                pd.put("userId", p.getString("id"));
                pd.put("list", list);
                perUserService.saveUserOrg(pd);
                objResult = new ObjResult(CommonCode.SUCCESS);
            }
        } catch (Exception e) {
            LOGGER.error(ExceptionUtils.getStackTrace(e));
            objResult = new ObjResult(CommonCode.ERROR);
        }
        return objResult;
    }

    /**
     * 获取集团下建的账号相关信息
     *
     * @return
     */
    public ObjResult getGroupPer(PageData pd) {
        try {
            //账号信息
            PageData user = userDao.findbyid(pd.getString("id"));
            if (StringUtil.isNotBlank(user.getString("phone"))){
                user.put("phone", EncryptUtil.decryptBase64(user.getString("phone"), BaseConstant.BASE64_KEY));
            }
            user.remove("password");
            //账号下的单位权限
            List<PageData> list = userOrgDao.queryUserOrg(user.getString("id"));
            //账号下的角色
            List<PageData> list1 = perUserOrgDao.queryPerUserGroup(user.getString("id"));

            //账号下的岗位
            List<PageData> list3 = userGroupRelationDao.getListByUserId(user.getString("id"));

            //返回给前端的集合
            List<PageData> list2 = new ArrayList<>();
            for (PageData pageData : list) {
                //当前单位下的角色
                List<PageData> l = new ArrayList<>();
                //当前单位下的岗位
                List<PageData> l1 = new ArrayList<>();
                //单位信息
                PageData org = new PageData();
                org.put("orgId", pageData.getString("orgId"));
                org.put("orgName", pageData.getString("orgName"));
                for (PageData pageData1 : list1) {
                    if (pageData.getString("userOrgId").equals(pageData1.getString("userOrgId"))) {
                        PageData p = new PageData();
                        p.put("groupId", pageData1.getString("GropupId"));
                        p.put("groupName", pageData1.getString("name"));
                        l.add(p);
                    }
                }

                for (PageData pageData1 : list3) {
                    if (pageData.getString("orgId").equals(pageData1.getString("orgId"))) {
                        PageData p = new PageData();
                        p.put("groupId", pageData1.getString("groupId"));
                        p.put("groupName", pageData1.getString("groupName"));
                        l1.add(p);
                    }
                }
                org.put("groups", l);
                org.put("postList", l1);
                list2.add(org);
            }
            user.put("list", list2);
            ObjResult objResult = new ObjResult(CommonCode.SUCCESS);
            objResult.setPageData(user);
            return objResult;
        } catch (Exception e) {
            LOGGER.error(ExceptionUtils.getStackTrace(e));
            throw new MyRuntimeException();
        }
    }

    private List<PageData> saveUserOrg(String userId, List<String> orgIds) throws Exception {
        if (orgIds == null || orgIds.size() <= 0) {
            userOrgDao.del_orgUser(userId);
        }
        //查询当前账号下的单位
        List<PageData> l = userOrgDao.queryUserOrg(userId);

        //得到不需要操作的列表
        List<String> l1 = new ArrayList<>();
        //所有权限的orgid
        List<String> l2 = new ArrayList<>();
        List<String> l3 = new ArrayList<>();
        List<PageData> list = new ArrayList<>();
        List<PageData> list1 = new ArrayList<>();
        if (l != null && l.size() > 0) {
            l.forEach(pageData -> {
                orgIds.forEach(s -> {
                    if (s.equals(pageData.getString("orgId"))) {
                        l1.add(pageData.getString("userOrgId"));
                        PageData p = new PageData();
                        p.put("id", pageData.getString("userOrgId"));
                        p.put("orgId", s);
                        list1.add(p);
                    }
                    l2.add(pageData.getString("userOrgId"));
                    l3.add(pageData.getString("orgId"));
                });
            });

            l.clear();
            //得到需要删除的列表,权限有,传来的id没有
            l2.removeAll(l1);
            //需要保存的列表,权限没有，传来的id有
            orgIds.removeAll(l3);
            l1.clear();
            l3.clear();
        }

        orgIds.forEach(s -> {
            PageData p = new PageData();
            String id = UuidUtil.get32UUID();
            p.put("userId", userId);
            p.put("id", id);
            p.put("orgId", s);
            list.add(p);
        });
        //批量删除
        if (l2 != null && l2.size() > 0) {
            userOrgDao.del_ids(l2);
        }
        //批量保存
        if (list != null && list.size() > 0) {
            userOrgDao.userOrgConfig(list);
            list1.addAll(list);
        }
        return list1;
    }

    /**
     * 修改
     *
     * @param p
     * @throws Exception
     */
    @Transactional(rollbackFor = RuntimeException.class)
    public ObjResult editGroup(PageData p) {
        ObjResult objResult;
        try {
            if (TokenUtil.getTokenUserId().equals(p.getString("id"))){
                objResult = new ObjResult("本账号正在登录使用，无法修改本账号数据");
                return objResult;
            }
            PageData p_user = userDao.findbyid(p.getString("id"));
            String userName = p_user.getString("username");
            String passWord = p.getString("password");
            if (Tools.notEmpty(passWord)) {
//                String ecpassword = new SimpleHash("SHA-1", userName, passWord).toString();    //密码加密
                p.put("password", passWord);
                p.put("passwordUpdateTime", new Date());
            } else {
                p.put("password", p_user.getString("password"));
                p.put("passwordUpdateTime", p_user.get("passwordUpdateTime"));
            }
            if (Tools.isEmpty(p.getString("type"))) {
                p.put("type", "3");
            } else {
                String type = p.getString("type");
                if (!"0".equals(type) && !"1".equals(type) && !"2".equals(type) && !"3".equals(type)) {
                    objResult = new ObjResult(CommonCode.VALIDATE);
                    objResult.setMessage("类型错误!");
                    return objResult;
                }
            }
            if (StringUtil.isNotBlank(p.getString("phone"))){
                p.put("phone", EncryptUtil.encryptBase64(p.getString("phone"), BaseConstant.BASE64_KEY));
            }
            boolean phoneFlag = StringUtil.equals(p_user.getString("phone"), p.getString("phone"));
            userDao.edit(p);
            String userId = p.getString("id");
            UserCache.update(userId);

            //保存账号-单位权限
            //需要保存的单位
            List<String> orgIds = new ArrayList<>();
            //前端传来旳集合
            List<HashMap<String, Object>> list = (List<HashMap<String, Object>>) p.get("list");

            //岗位集合
            List<PageData> postList = new ArrayList<>();
            //拿到单位id
            for (HashMap<String, Object> stringObjectHashMap : list) {
                orgIds.add(stringObjectHashMap.get("orgId").toString());
                List<HashMap<String, Object>> list1 = (List<HashMap<String, Object>>) stringObjectHashMap.get("postList");
                if(CollectionUtil.isNotEmpty(list1)){
                    for (HashMap<String, Object> objectHashMap : list1) {
                        PageData params = new PageData();
                        params.put("id", userId);
                        PageData pageData = new PageData();
                        pageData.put("id", UuidUtil.get32UUID());
                        pageData.put("userId", userId);
                        pageData.put("userName", userName);
                        pageData.put("groupId", objectHashMap.get("groupId").toString());
                        pageData.put("groupName", objectHashMap.get("groupName").toString());
                        pageData.put("organizationId", stringObjectHashMap.get("orgId").toString());
                        postList.add(pageData);
                    }
                }
            }
            userGroupRelationDao.deleteByUserId(userId);
            if (postList != null && postList.size() > 0) {
                PageData pageData = new PageData();
                pageData.put("pageDataList", postList);
                userGroupRelationDao.insertBatch(pageData);
            }

            //拿到单位-账号集合
            List<PageData> groupIds = saveUserOrg(p.getString("id"), orgIds);
            for (HashMap<String, Object> stringObjectHashMap : list) {
                for (PageData p2 : groupIds) {
                    if (stringObjectHashMap.get("orgId").toString().equals(p2.getString("orgId"))) {
                        stringObjectHashMap.put("userOrgId", p2.getString("id"));
                    }
                }
            }


            PageData pd = new PageData();
            pd.put("userId", p.getString("id"));
            pd.put("list", list);
            perUserService.saveUserOrg(pd);
            if (!phoneFlag){
                p.put("oriPhone", p_user.getString("phone"));
                p.put("newPhone", p.getString("phone"));
            }
            objResult = new ObjResult(CommonCode.SUCCESS);
        } catch (Exception e) {
            LOGGER.error(ExceptionUtils.getStackTrace(e));
            objResult = new ObjResult(CommonCode.ERROR);
            return objResult;
        }
        return objResult;
    }


    /**
     * 修改
     *
     * @param p
     * @throws Exception
     */
    public ObjResult edit(PageData p) {
        ObjResult objResult;
        try {
            PageData p_user = userDao.findbyid(p.getString("id"));
            String userName = p_user.getString("username");
            String passWord = p.getString("password");
            if (Tools.notEmpty(passWord)) {
//                String ecpassword = new SimpleHash("SHA-1", userName, passWord).toString();    //密码加密
                p.put("password", passWord);
                p.put("passwordUpdateTime", new Date());
            } else {
                p.put("password", p_user.getString("password"));
                p.put("passwordUpdateTime", p_user.get("passwordUpdateTime"));
            }
            if (Tools.isEmpty(p.getString("type"))) {
                p.put("type", "3");
            } else {
                String type = p.getString("type");
                if (!"0".equals(type) && !"1".equals(type) && !"2".equals(type) && !"3".equals(type)) {
                    objResult = new ObjResult(CommonCode.VALIDATE);
                    objResult.setMessage("类型错误!");
                    return objResult;
                }
            }
            if (StringUtil.isNotBlank(p.getString("phone"))){
                p.put("phone", EncryptUtil.encryptBase64(p.getString("phone"), BaseConstant.BASE64_KEY));
            }
            p.put("updateTime", DateUtil.now());
            userDao.edit(p);
            boolean phoneFlag = StringUtil.equals(p_user.getString("phone"), p.getString("phone"));
            if (!phoneFlag){
                p.put("oriPhone", p_user.getString("phone"));
                p.put("newPhone", p.getString("phone"));
            }
            UserCache.update(p.getString("id"));
            objResult = new ObjResult(CommonCode.SUCCESS);
        } catch (Exception e) {
            LOGGER.error(ExceptionUtils.getStackTrace(e));
            objResult = new ObjResult(CommonCode.ERROR);
            return objResult;
        }
        return objResult;
    }

    public ObjResult userEdit(PageData p) {
        try {
            PageData user = userDao.findbyid(TokenUtil.getTokenUserId());
            //密码
            String password = p.getString("password");
            //原密码
            String pastPassword = p.getString("pastPassword");
            ObjResult objResult;
            //密码加密
//            String pastecpassword = new SimpleHash("SHA-1", userName, pastPassword).toString();
            if (Tools.notEmpty(password)) {
                if (!pastPassword.equals(user.getString("password"))) {
                    objResult = new ObjResult(CommonCode.ERRORPARAMETER);
                    objResult.setMessage("原密码错误!!");
                    return objResult;
                } else {
                    if (password.equals(pastPassword)) {
                        objResult = new ObjResult(CommonCode.ERRORPARAMETER);
                        objResult.setMessage("密码不可相同!!");
                        return objResult;
                    }

                    user.put("isInitialPassword", 1);
                    user.put("password", password);
                    if (StringUtil.isNotBlank(user.getString("phone"))){
                        user.put("phone", EncryptUtil.encryptBase64(user.getString("phone"), BaseConstant.BASE64_KEY));
                    }
                    user.put("passwordUpdateTime", new Date());
                    userDao.edit(user);
                    UserCache.update(user.getString(user.getString("id")));
                    objResult = new ObjResult(CommonCode.SUCCESS);
                    return objResult;
                }
            } else {
                objResult = new ObjResult(CommonCode.ERRORPARAMETER);
                objResult.setMessage("密码不可为空!!");
                return objResult;
            }
        } catch (Exception e) {
            LOGGER.error(ExceptionUtils.getStackTrace(e));
            throw new MyRuntimeException();
        }
    }

    /**
     * 根据id查询
     *
     * @param p
     * @throws Exception
     */
    public ObjResult findbyid(PageData p) {
        ObjResult objResult;
        try {
            PageData p_user = userDao.findbyid(p.getString("id"));
            objResult = new ObjResult(CommonCode.SUCCESS);
            if (StringUtil.isNotBlank(p_user.getString("phone"))){
                p_user.put("phone", EncryptUtil.decryptBase64(p_user.getString("phone"), BaseConstant.BASE64_KEY));
            }
            objResult.setPageData(p_user);
        } catch (Exception e) {
            LOGGER.error(ExceptionUtils.getStackTrace(e));
            objResult = new ObjResult(CommonCode.ERROR);
            return objResult;
        }
        return objResult;
    }

    public ListResult findByIds(List<String> ids) {
        ListResult<PageData> listResult;
        try {
            listResult = new ListResult<>(CommonCode.SUCCESS);
            List<PageData> userList = userDao.findByIds(ids);
            for (PageData user : userList){
                if (StringUtil.isNotBlank(user.getString("phone"))){
                    user.put("phone", EncryptUtil.decryptBase64(user.getString("phone"), BaseConstant.BASE64_KEY));
                }
            }
            listResult.setList(userList);
        } catch (Exception e) {
            LOGGER.error(ExceptionUtils.getStackTrace(e));
            listResult = new ListResult<>(CommonCode.ERROR);
        }
        return listResult;
    }

    @Cacheable(value = "getUserId", key = "#userId")
    public String findIdForName(String userId) {
        try {
            PageData p_user = userDao.findbyid(userId);
            if (CollectionUtil.isEmpty(p_user)){
                return "";
            }
            return Tools.notEmpty(p_user.getString("name")) ? p_user.getString("name") : "";
        } catch (Exception e) {
            LOGGER.error(ExceptionUtils.getStackTrace(e));
            ObjResult objResult = new ObjResult(CommonCode.ERROR);
            throw new MyRuntimeException(objResult);
        }
    }

    /**
     * 删除
     *
     * @throws Exception
     */
    public ObjResult delids(List<String> list) {
        ObjResult objResult;
        try {
            List<PageData> userList = userDao.findByIds(list);
            userDao.del_ids(list);
            UserCache.evictBatch(list);
            objResult = new ObjResult(CommonCode.SUCCESS);
        } catch (Exception e) {
            LOGGER.error(ExceptionUtils.getStackTrace(e));
            objResult = new ObjResult(CommonCode.ERROR);
            return objResult;
        }
        return objResult;
    }

    /**
     * 用户列表分页
     *
     * @param pd
     * @return
     */
    public ListResult<PageData> listpage(PageData pd) {
        try {
            Page page = new Page(true, pd);
            if (Tools.notEmpty(pd.getString("keywords"))) {
                pd.put("keyword", pd.getString("keywords"));
            }
            String keyword = pd.getString("keyword");
            if (Tools.notEmpty(keyword)) {
                keyword = keyword.replaceAll("_", "/_");
                pd.put("keyword", keyword.trim());
            }
            List<PageData> list = userDao.list(page);
            for (PageData user : list){
                if (StringUtil.isNotBlank(user.getString("phone"))){
                    user.put("phone", EncryptUtil.decryptBase64(user.getString("phone"), BaseConstant.BASE64_KEY));
                }
            }
            ListResult<PageData> Result = new ListResult<>(CommonCode.SUCCESS);
            Result.setList(list);
            Result.setTotal(page.getTotal());
            return Result;
        } catch (Exception e) {
            LOGGER.error(ExceptionUtils.getStackTrace(e));
            return new ListResult<>(CommonCode.ERROR);
        }
    }

    /**
     * 创建人创建的账号
     *
     * @param pd
     * @return
     */
    public ListResult<PageData> listByCreatUser(PageData pd) {
        try {
            //当前单位id
            String orgId = TokenUtil.getTokenOrgId();
            //拿到所有单位
            List<PageData> orgAll = orgzationDao.list(null);
            //递归拿到当前单位下的子集
            TreeUtli treeUtli = new TreeUtli();
            List<PageData> l = treeUtli.getChlidList(orgId, orgAll, null);
            //拿到当前单位及下属单位id
            List<String> orgs = l.stream().map(pageData -> pageData.getString("id")).collect(Collectors.toList());
            orgs.add(orgId);
            pd.put("orgIds", orgs);
            Page page = new Page(true, pd);
            String keyword = pd.getString("keyword");
            if (Tools.notEmpty(keyword)) {
                keyword = keyword.replaceAll("_", "/_");
                pd.put("keyword", keyword.trim());
            }
            List<PageData> list = userDao.listByCreatUser(page);

            if (CollectionUtil.isNotEmpty(list)) {
                for (PageData user : list) {
                    String loginErrNumKey = userLoginErrNum + user.getString("id");
                    if (StringUtil.isNotBlank(user.getString("phone"))){
                        user.put("phone", EncryptUtil.decryptBase64(user.getString("phone"), BaseConstant.BASE64_KEY));
                    }
                    if (redisUtils.hasKey(loginErrNumKey)) {
                        int loginErrNum = (Integer) redisUtils.get(loginErrNumKey);
                        if (loginErrNum >= 10) {
                            user.put("isLocked", 2);
                        }
                    }
                }
            }
            ListResult<PageData> Result = new ListResult<>(CommonCode.SUCCESS);
            Result.setList(list);
            Result.setTotal(page.getTotal());
            return Result;
        } catch (Exception e) {
            LOGGER.error(ExceptionUtils.getStackTrace(e));
            return new ListResult<>(CommonCode.ERROR);
        }
    }

    /**
     * 解锁
     *
     * @param id
     * @return
     */
    public ObjResult unlock(String id) {
        String loginErrNumKey = userLoginErrNum + id;
        if (!redisUtils.hasKey(loginErrNumKey)) {
            return new ObjResult(CommonCode.FAIL);
        }
        return redisUtils.delOne(loginErrNumKey)
                ? new ObjResult(CommonCode.SUCCESS) : new ObjResult(CommonCode.FAIL);
    }

    /**
     * 登录校验
     *
     * @param pd
     * @return
     */
    public ObjResult login(PageData pd) {
        //根据账号和用户名得到用户信息
        ObjResult objResult;
        long beginTime = System.currentTimeMillis();
        //日志信息
        Loginfo log = new Loginfo();
        log.setId(UuidUtil.get32UUID());
        log.setOperation("登录");
        HttpServletRequest request = HttpContextUtils.getHttpServletRequest(); //  获取request
        log.setCallingInterface(request.getRequestURI());
        log.setRequestWay(request.getMethod());
        log.setIp(IpUtils.getIpAddr(request));
        log.setUserAgent(request.getHeader(HttpHeaders.USER_AGENT));
        log.setRequestParams(pd.toString());
        log.setUserName(pd.getString("username"));
        try {
            String username = pd.getString("username");
            String ecpassword = pd.getString("password");
//            String ecpassword = new SimpleHash("SHA-1", username, password).toString();    //密码加密
            PageData pd_user = userDao.getUser(username);
            if (pd_user == null) {
                log.setLogType(3);
                log.setStatus(LogStatusEnum.FAIL.value());
                log.setRequestTime(cn.hutool.core.date.DateUtil.date());
                long time = System.currentTimeMillis() - beginTime;
                log.setRequestDuration(time);
                log.setErrorInfo("用户："+username+"不存在！");
                loginfoMapper.save(log);
                objResult = new ObjResult(CommonCode.LOGIN_FHIL);
                objResult.setMessage("用户："+username+"不存在！");
                return objResult;
            }
            objResult = checkPassword(pd_user, ecpassword, log, beginTime);

            if (!objResult.isSuccess()) {
                return objResult;
            }
            Integer status = pd_user.getInteger("status");
            if(null != status && 1 != status){
                log.setLogType(3);
                log.setStatus(LogStatusEnum.FAIL.value());
                log.setRequestTime(cn.hutool.core.date.DateUtil.date());
                long time = System.currentTimeMillis() - beginTime;
                log.setRequestDuration(time);
                log.setErrorInfo("登录失败，用户已停用！");
                loginfoMapper.save(log);
                objResult = new ObjResult(CommonCode.LOGIN_FHIL);
                objResult.setMessage("登录失败，用户已停用！");
                return objResult;
            }
            objResult = userInfoToResult(pd_user, pd, log, beginTime);
        } catch (Exception e) {
            LOGGER.error(ExceptionUtils.getStackTrace(e));
            objResult = new ObjResult(CommonCode.ERROR);
            return objResult;
        }
        log.setLogType(1);
        log.setStatus(LogStatusEnum.SUCCESS.value());
        log.setRequestTime(cn.hutool.core.date.DateUtil.date());
        long time = System.currentTimeMillis() - beginTime;
        log.setRequestDuration(time);
        loginfoMapper.save(log);
        return objResult;
    }

    private ObjResult checkPassword(PageData pd_user, String ecpassword, Loginfo log, long beginTime){
        ObjResult objResult = new ObjResult(CommonCode.SUCCESS);

        String userId = pd_user.getString("id");
        String loginErrNumKey = userLoginErrNum + userId;
        int loginErrNum = 0;
        if (redisUtils.hasKey(loginErrNumKey)) {
            loginErrNum = (Integer) redisUtils.get(loginErrNumKey);
        }
        if (loginErrNum >= 10) {
            log.setLogType(3);
            log.setStatus(LogStatusEnum.FAIL.value());
            log.setRequestTime(cn.hutool.core.date.DateUtil.date());
            long time = System.currentTimeMillis() - beginTime;
            log.setRequestDuration(time);
            log.setErrorInfo("密码错误10次！请一小时后再试");
            loginfoMapper.save(log);
            objResult = new ObjResult(CommonCode.LOGIN_FHIL);
            objResult.setMessage("密码错误10次！请一小时后再试");
            return objResult;
        }
        if (!ecpassword.equals(pd_user.getString("password"))) {
            log.setLogType(3);
            log.setStatus(LogStatusEnum.FAIL.value());
            log.setRequestTime(cn.hutool.core.date.DateUtil.date());
            long time = System.currentTimeMillis() - beginTime;
            log.setRequestDuration(time);
            log.setErrorInfo("密码错误");
            loginfoMapper.save(log);
            objResult = new ObjResult(CommonCode.LOGIN_FHIL);
            redisUtils.set(loginErrNumKey, ++loginErrNum, loginErrNumTime);
            return objResult;
        }
        if (loginErrNum > 0) {
            //登录成功 清零
            redisUtils.del(loginErrNumKey);
        }
        return objResult;
    }

    private ObjResult userInfoToResult(PageData pd_user, PageData pd, Loginfo log, long beginTime){
        ObjResult objResult;
        try {
            String officeId = pd_user.getString("officeId");
            String TYPE = pd_user.getString("type");
            //是否为企业账号

            List<PageData> list = userOrgDao.queryUserOrg(pd_user.getString("id"));
            //判断是否验证单位权限
            if (pd.containsKey("orgId")) {
                //判断是否存在orgId
                List<PageData> l = list.stream().filter(pageData -> pageData.getString("orgId").equals(pd.getString("orgId"))).collect(Collectors.toList());
                if (l != null && l.size() > 0) {
                    //获取token
                    PageData p_token = new PageData();
                    p_token.put("type", TYPE);
                    p_token.put("username", pd_user.getString("username"));
                    p_token.put("password", pd_user.getString("password"));
                    p_token.put("id", pd_user.getString("id"));
                    p_token.put("orgId", pd.getString("orgId"));
                    String token = tokenService.getToken(p_token);
                    //返回给前端
                    PageData result = new PageData();
                    result.put("token", token);
                    result.put("longToken", tokenService.getLongToken(p_token));
                    result.put("type", TYPE);
                    result.put("username", pd_user.getString("username"));
                    result.put("isInitialPassword", pd_user.getInteger("isInitialPassword"));
                    result.put("gzwId", orgzationService.getGzwId());
                    result.put("isGzw", orgService.checkIsGzw(pd.getString("orgId")) ? 1 : 0);
                    //是否市国资委   1否2是
                    result.put("gzwFlag", orgzationService.checkGzwName(
                            orgzationService.getCompetentOrganization(pd.getString("orgId"))) ? 2 : 1);
                    //是否考核
                    result.put("isAssess",officeService.checkAssess(officeId)?1:0);
                    //是否财管处
                    result.put("isCgc",officeService.checkFinancialManagement(pd.getString("orgId"),officeId)?1:0);


                    objResult = new ObjResult(CommonCode.SUCCESS);
                    objResult.setPageData(result);
                    User user = new User();
                    user.setId(pd.getString("id"));
                    user.setNickname(pd.getString("name"));
                    SessionHelper.setUser(user);
                    SessionHelper.setOrganizationId(pd.getString("orgId"));
                    return objResult;
                } else {
                    log.setLogType(3);
                    log.setStatus(LogStatusEnum.FAIL.value());
                    log.setRequestTime(cn.hutool.core.date.DateUtil.date());
                    long time = System.currentTimeMillis() - beginTime;
                    log.setRequestDuration(time);
                    log.setErrorInfo("无单位权限");
                    loginfoMapper.save(log);
                    objResult = new ObjResult(CommonCode.ERROR);
                    objResult.setMessage("无单位权限");
                    return objResult;
                }
            } else {
                PageData p1 = new PageData();
                PageData p_token = new PageData();
                p_token.put("type", TYPE);
                p_token.put("username", pd_user.getString("username"));
                p_token.put("password", pd_user.getString("password"));
                p_token.put("id", pd_user.getString("id"));
                p1.put("username", pd.getString("username"));
                p1.put("password", pd.getString("password"));
                p1.put("type", TYPE);
                if (!"0".equals(TYPE)) {
                    if (list != null && list.size() > 0) {
                        if (list.size() == 1) {
                            p_token.put("orgId", list.get(0).getString("orgId"));
                            String token = tokenService.getToken(p_token);
                            p1.put("token", token);
                            String longToken = tokenService.getLongToken(p_token);
                            p1.put("longToken", longToken);
                            p1.put("list", list);
                            //是否市国资委   1否2是
                            p1.put("gzwFlag", orgzationService.checkGzwName(orgzationService
                                    .getCompetentOrganization(list.get(0).getString("orgId"))) ? 2 : 1);
                            p1.put("isGzw", orgService.checkIsGzw(list.get(0).getString("orgId")) ? 1 : 0);
                            //是否考核
                            p1.put("isAssess",officeService.checkAssess(officeId)?1:0);
                            //是否财管处
                            p1.put("isCgc",officeService.checkFinancialManagement(list.get(0).getString("orgId"),officeId)?1:0);
                        } else {
                            list.forEach(pageData -> {
                                pageData.put("title", pageData.getString("orgName"));
                            });
                            p1.put("list", list);
                        }
                    } else {
                        log.setLogType(3);
                        log.setStatus(LogStatusEnum.FAIL.value());
                        log.setRequestTime(cn.hutool.core.date.DateUtil.date());
                        long time = System.currentTimeMillis() - beginTime;
                        log.setRequestDuration(time);
                        log.setErrorInfo("无单位权限");
                        loginfoMapper.save(log);
                        objResult = new ObjResult(CommonCode.ERROR);
                        objResult.setMessage("无单位权限");
                        return objResult;
                    }
                } else {
                    p_token.put("orgId", null);
                    String token = tokenService.getToken(p_token);
                    p1.put("token", token);
                    String longToken = tokenService.getLongToken(p_token);
                    p1.put("longToken", longToken);
                }
                objResult = new ObjResult(CommonCode.SUCCESS);
                String defaultTime = bulletinService.getDefaultTime().getString("reportTime");
                String investmentTime = baseInvestmentExecutionMapper.getDefaultTime(defaultTime);
                if (StringUtil.isNotBlank(investmentTime) &&
                        DateUtil.parse(defaultTime, DateUtil.PATTERN_MONTH).getTime() > DateUtil.parse(investmentTime, DateUtil.PATTERN_MONTH).getTime()){
                    defaultTime = investmentTime;
                }
                p1.put("reportTime", defaultTime);
                p1.put("isInitialPassword", pd_user.getInteger("isInitialPassword"));
                Date date = (Date)pd_user.get("passwordUpdateTime");
                p1.put("passwordMessageFlag", "1");
                if (date != null && (DateUtil.now().getTime() - date.getTime()) > threeMonthTime){
                    p1.put("passwordMessageFlag", "2");
                }

                objResult.setPageData(p1);
                User user = new User();
                user.setId(pd.getString("id"));
                user.setNickname(pd.getString("name"));
                SessionHelper.setUser(user);
                SessionHelper.setOrganizationId(pd.getString("orgId"));
            }
        } catch (Exception e) {
            LOGGER.error(ExceptionUtils.getStackTrace(e));
            objResult = new ObjResult(CommonCode.ERROR);
            return objResult;
        }
        return objResult;
    }

    /**
     * 获取系统信息
     *
     * @return
     */
    public ObjResult getSystem() {
        String userId = TokenUtil.getTokenUserId();
        ObjResult objResult;
        try {
            PageData user = userDao.findbyid(userId);
            PageData pd = new PageData();
            String type = user.getString("type");
            pd.put("username", user.getString("username"));
            pd.put("name", user.getString("name"));
            pd.put("type", user.getString("type"));
            pd.put("userId", user.getString("id"));
            pd.put("isInitialPassword", user.getInteger("isInitialPassword"));
            String officeId = user.getString("officeId");
            if (Optional.ofNullable(officeId).isPresent()){
                pd.put("officeId", officeId);
                Office office = officeService.getById(officeId);
                if (Optional.ofNullable(office).isPresent()){
                    pd.put("officeName",office.getName());
                }
            }

//            if (type.equals("3")) {
            String orgId = TokenUtil.getTokenOrgId();
            PageData org = orgzationDao.findbyid(orgId);
            if (org != null) {
                pd.put("orgName", org.getString("name"));
                pd.put("orgId", org.getString("id"));
                pd.put("gzwFlag", orgzationService.checkGzwName(
                        orgzationService.getCompetentOrganization(pd.getString("orgId"))) ? 2 : 1);
            }
//            }
            objResult = new ObjResult(CommonCode.SUCCESS);
            String defaultTime = bulletinService.getDefaultTime().getString("reportTime");
            String investmentTime = baseInvestmentExecutionMapper.getDefaultTime(defaultTime);
            if (StringUtil.isNotBlank(investmentTime) &&
                    DateUtil.parse(defaultTime, DateUtil.PATTERN_MONTH).getTime() > DateUtil.parse(investmentTime, DateUtil.PATTERN_MONTH).getTime()){
                defaultTime = investmentTime;
            }
            pd.put("reportTime", defaultTime);
            objResult.setPageData(pd);
        } catch (Exception e) {
            LOGGER.error(ExceptionUtils.getStackTrace(e));
            throw new MyRuntimeException(new ObjResult(CommonCode.ERROR));
        }
        return objResult;
    }

    public User getCurrentUser() {
        String userId = TokenUtil.getTokenUserId();
        PageData pageData = new PageData();
        pageData.put("id", userId);
        PageData pd = findbyid(pageData).getPageData();
        User user = new User();
        user.setId(userId);
        user.setNickname(pd.getString("name"));
        return user;
    }

    public ListResult<PageData> selectByOrganizationId(PageData pd) {
        try {
            List<String> strings = userOrgDao.selectByOrganizationId(pd);
            List<PageData> collect = strings.stream().map(userId -> {
                try {
                    return userDao.findbyid(userId);
                } catch (Exception e) {
                    LOGGER.error(ExceptionUtils.getStackTrace(e));
                    throw new MyRuntimeException("根据用户id获取用户时失败！");
                }
            }).collect(Collectors.toList());
            for (PageData user : collect){
                if (StringUtil.isNotBlank(user.getString("phone"))){
                    user.put("phone", EncryptUtil.decryptBase64(user.getString("phone"), BaseConstant.BASE64_KEY));
                }
            }
            ListResult<PageData> result = new ListResult<>(CommonCode.SUCCESS);
            result.setList(collect);
            return result;
        } catch (Exception e) {
            LOGGER.error(ExceptionUtils.getStackTrace(e));
            return new ListResult<>(CommonCode.ERROR);
        }
    }

    /**
     * 找到下级单位权限的账号
     *
     * @param pd
     * @return
     */
    public ListResult<PageData> listForLowerUnit(PageData pd) {
        try {
            ListResult<PageData> Result = new ListResult<>(CommonCode.SUCCESS);
            PageData pageData = userDao.findbyid(TokenUtil.getTokenUserId());
            //判断当前单位的单位类型
            if (StringUtil.isNotBlank(pageData.getString("phone"))){
                pageData.put("phone", EncryptUtil.decryptBase64(pageData.getString("phone"), BaseConstant.BASE64_KEY));
            }
            switch (pageData.getString("type")) {
                //  管理员；
                case "0":
                    Result.setList(null);
                    break;
                //  国资端；
                case "1":
                    PageData findPd = new PageData();
                    findPd.put("type", String.valueOf(1));
                    List<PageData> listgz = userDao.findListByType(findPd);
                    Result.setList(listgz);
                    break;
                //  领导端；
                case "2":
                    Result.setList(null);
                    break;
                //  企业账号；
                case "3":
                    //找到当前账号下属单位权限
                    List<PageData> userOrg = userOrgDao.findLowerUnit(TokenUtil.getTokenUserId());
                    String uo = "";
                    if (userOrg.size() > 0) {
                        for (PageData p :
                                userOrg) {
                            uo += "'" + p.getString("orgId") + "',";
                        }
                        uo = uo.substring(0, uo.length() - 1);
                        List<PageData> listqy = userDao.findByorg(uo);
                        Result.setList(listqy);
                    }
                    break;
                default:
                    Result.setMessage("未定义的单位类型！");
            }
            return Result;
        } catch (Exception e) {
            LOGGER.error(ExceptionUtils.getStackTrace(e));
            return new ListResult<>(CommonCode.ERROR);
        }
    }

    public ListResult<PageData> getUsersUnderGZW() {
        try {
            List<PageData> usersUnderGZW = userDao.getUsersUnderGZW();
            ListResult<PageData> result = new ListResult<>(CommonCode.SUCCESS);
            for (PageData user : usersUnderGZW){
                if (StringUtil.isNotBlank(user.getString("phone"))){
                    user.put("phone", EncryptUtil.decryptBase64(user.getString("phone"), BaseConstant.BASE64_KEY));
                }
            }
            result.setList(usersUnderGZW);
            return result;
        } catch (Exception e) {
            LOGGER.error(ExceptionUtils.getStackTrace(e));
            return new ListResult<>(CommonCode.ERROR);
        }
    }

    /**
     * 校验导入数据  企业名称
     * @param importUsers
     */
    private void checkData(List<PageData> importUsers, List<PageData> oldUsers){
        List<String> oldUserNames = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(oldUsers)){
            oldUserNames = oldUsers.stream().map(p -> p.getString("username")).collect(Collectors.toList());
        }

        List<PageData> orgList = orgzationService.getSubordinateList();
        List<String> orgNames = orgList.stream().map(p -> p.getString("name")).collect(Collectors.toList());
        List<String> checkMessage = new ArrayList<>();
        List<String> insertUserNames = new ArrayList<>();
        List<String> oldUserCompanyList = new ArrayList<>();
        for (PageData importUser : importUsers){
            String username = importUser.getString("username");
            String orgName = importUser.getString("orgName");

            if (!oldUserNames.contains(username)){
                if (insertUserNames.contains(username + "-" + orgName)){
                    checkMessage.add(username + "该新增用户," + orgName + "单位重复");
                }else {
                    insertUserNames.add(username + "-" + orgName);
                }
            }else {
                if (oldUserCompanyList.contains(username + "-" + orgName)){
                    checkMessage.add(username + "该老用户," + orgName + "单位重复");
                }else {
                    oldUserCompanyList.add(username + "-" + orgName);
                }
            }

            if (!orgNames.contains(orgName)){
                checkMessage.add(username+ "，" + orgName + "该单位无权限导入");
            }
        }

        ObjResult objResult = new ObjResult(CommonCode.FAIL);
        if (CollectionUtil.isNotEmpty(checkMessage)){
            objResult.setMessage(checkMessage.stream().collect(Collectors.joining(",")));
            throw new MyRuntimeException(objResult);
        }
    }
    /**
     * 账号导入
     *
     * @param mp
     * @return
     */
    @Transactional
    public ObjResult upLoadExlce(MultipartHttpServletRequest mp) {
        try {
            Workbook book;
            if ("application/vnd.ms-excel".equals(mp.getContentType())) {
                book = new HSSFWorkbook(mp.getFile("file").getInputStream());
            } else {
                book = new XSSFWorkbook(mp.getFile("file").getInputStream());
            }

            Sheet sheet = book.getSheetAt(0);
            UploadUtil uploadUtil = new UploadUtil();

            String[] titles_name = {
                    "账户",
                    "名称",
                    "密码",
                    "企业名称",
                    "角色权限",
                    "审核岗位"
            };
            String[] sql_name = {
                    "username",
                    "name",
                    "password",
                    "orgName",
                    "roles",
                    "posts"
            };
            //读取excel的账号列表
            List<PageData> list = new ArrayList<>();
            for (int rowNum = 1; rowNum <= sheet.getLastRowNum(); rowNum++) {
                Row row = sheet.getRow(rowNum);
                if (null == row) {
                    continue;
                }
                PageData user = new PageData();
                //遍历列
                boolean flag = false;
                for (int cellNum = 0; cellNum <= row.getLastCellNum(); cellNum++) {
                    Cell cell = row.getCell(cellNum);
                    if (null == cell) {
                        continue;
                    }
                    for (int i = 0; i < titles_name.length; i++) {
                        if (uploadUtil.getCellValue(sheet.getRow(0).getCell(cellNum)).trim().equals(titles_name[i])) {
                            if (StringUtil.isNotBlank(uploadUtil.getCellValue(cell))){
                                flag = true;
                                user.put(sql_name[i], uploadUtil.getCellValue(cell));
                            }

                        }
                    }
                }
                if (flag){
                    list.add(user);
                }
            }
            if (list == null || list.size() <= 0) {
                ObjResult objResult = new ObjResult(CommonCode.FAIL);
                objResult.setMessage("请在模板添加数据");
                throw new MyRuntimeException(objResult);
            } else {
                List<PageData> oldUsers = userDao.findByUsernames(list);

                Map<String, String> oldUserNameIdMap = new HashMap<>();
                if(CollectionUtil.isNotEmpty(oldUsers)){
                    oldUserNameIdMap = oldUsers.stream().collect(Collectors
                            .toMap(p -> p.getString("username"), p -> p.getString("id"), (k1,k2) -> k1));
                }
                checkData(list, oldUsers);
                //账号集合
                List<PageData> list_user = new ArrayList<>();
                //用户-单位权限
                List<PageData> list_uo = new ArrayList<>();
                //用户-角色
                List<PageData> list_role = new ArrayList<>();
                //用户-岗位
                List<PageData> list_post = new ArrayList<>();
                //单位-账号权限集合
                String thisUserId = TokenUtil.getTokenUserId();
                //拿到单位的列表
                List<PageData> orgs = orgzationDao.list(null);
                //岗位集合
                List<PageData> l_posts=workFlowGroupDao.list();
                //角色集合
                List<PageData> l_roles=perGroupDao.listAll();

                Map<String, String> addUserNameIdMap = new HashMap<>();
                //循环处理数据
                for (PageData pageData : list) {
                    //账号id
                    String userId = UuidUtil.get32UUID();
                    String username = pageData.getString("username");

                    //单位id
                    String orgId = "";
                    String orgName = pageData.getString("orgName").trim();
                    for (PageData org : orgs) {
                        if (org.getString("name").trim().equals(orgName) &&
                                TokenUtil.getCompetentOrganization().equals(orgzationService.getCompetentOrganization(org, orgs, org.getString("id")))) {
                            orgId = org.getString("id");
                            break;
                        }
                    }
                    //单位权限id
                    String uoId = UuidUtil.get32UUID();
                    boolean userFlag = true;
                    boolean userOrgFlag = true;
                    if(oldUserNameIdMap.containsKey(username)){
                        userFlag = false;
                        userId = oldUserNameIdMap.get(username);
                        PageData userOrgQuery = new PageData();
                        userOrgQuery.put("userId", userId);
                        userOrgQuery.put("orgId", orgId);
                        PageData userOrg = userOrgDao.querySingleUserOrg(userOrgQuery);

                        if (Optional.ofNullable(userOrg).isPresent()
                                && StringUtil.isNotBlank(userOrg.getString("userOrgId"))){
                            userOrgFlag = false;
                            //若该用户在该单位下配置过权限 则删除老数据
                            uoId = userOrg.getString("userOrgId");
                            perUserOrgDao.delByUserOrgId(uoId);
                            userGroupRelationDao.deleteByUserIdAndOrgId(userOrgQuery);
                        }

                    }
                    //账号
                    PageData u = new PageData();
                    u.put("username", username);
                    u.put("name", pageData.getString("name"));
                    u.put("type", "3");
                    u.put("creatDate", new Date());
                    u.put("creatUser", thisUserId);
                    u.put("isGroupAdmin", "0");
                    //u.put("phone","");
                    u.put("id", userId);
                    //密码加密
                    String ecpassword = new SimpleHash("SHA-1", pageData.getString("username"), pageData.getString("password")).toString();
                    u.put("password", ecpassword);
                    if (userFlag){
                        if(!addUserNameIdMap.containsKey(username)){
                            list_user.add(u);
                            addUserNameIdMap.put(username, userId);
                        }else {
                            userId = addUserNameIdMap.get(username);
                        }

                    }

                    //处理单位-用户权限
                    PageData uo = new PageData();
                    uo.put("orgId", orgId);
                    uo.put("userId", userId);
                    uo.put("id", uoId);
                    if (userOrgFlag){
                        list_uo.add(uo);
                    }

                    //处理角色
                    String rolesStr = pageData.getString("roles");
                    if (StringUtil.isNotBlank(rolesStr)){
                        String[] roles = rolesStr.split(",|，");
                        for (String role : roles) {
                            PageData r = new PageData();
                            String groupId="";
                            for (PageData ro : l_roles) {
                                if(Tools.notEmpty(ro.getString("code"))&&
                                        ro.getString("code").equals(role.trim())
                                ){
                                    groupId=ro.getString("id");
                                    break;
                                }
                            }
                            if(Tools.notEmpty(groupId)){
                                r.put("groupId", groupId);
                                r.put("userOrgId", uoId);
                                r.put("id",UuidUtil.get32UUID());
                                list_role.add(r);
                            }
                        }
                    }


                    //处理岗位
                    if (pageData.containsKey("posts")){
                        String[] posts = pageData.getString("posts").split(",|，");
                        for (String post : posts) {
                            PageData p = new PageData();

                            String groupId="";
                            String groupName="";
                            for (PageData po : l_posts) {
                                if(Tools.notEmpty(po.getString("code"))&&
                                        po.getString("code").equals(post)){
                                    groupName=po.getString("name");
                                    groupId=po.getString("id");
                                    break;
                                }
                            }
                            if(Tools.notEmpty(groupId)){
                                p.put("id", UuidUtil.get32UUID());
                                p.put("userId", userId);
                                p.put("userName", pageData.getString("username"));
                                p.put("groupId", groupId);
                                p.put("groupName", groupName);
                                p.put("organizationId", orgId);
                                list_post.add(p);
                            }
                        }
                    }
                }
                if (CollectionUtil.isNotEmpty(list_user)){
                    userDao.saveAll(list_user);
                }
                if (CollectionUtil.isNotEmpty(list_uo)) {
                    userOrgDao.userOrgConfig(list_uo);
                }
                if (CollectionUtil.isNotEmpty(list_role)) {
                    perUserOrgDao.PerUserOrgConfig(list_role);
                }

                if (CollectionUtil.isNotEmpty(list_post)){
                    PageData pageDataList=new PageData();
                    pageDataList.put("pageDataList",list_post);
                    userGroupRelationDao.insertBatch(pageDataList);
                }
                return new ObjResult(CommonCode.SUCCESS);
            }
        } catch (MyRuntimeException e) {
            throw e;
        } catch (Exception e) {
            LOGGER.error(ExceptionUtils.getStackTrace(e));
            throw new MyRuntimeException();
        }

    }


    /**
     *  生成可以导入的excel文件 并返回文件名  时间戳+"-"+uuid
     * @return
     */
    public ObjResult exportImportFile(){
        ObjResult objResult;
        try {
            PageData pd = new PageData();
            pd.put("orgIds", orgzationService.getSubordinateIds());
            List<UserRoleInfoVO> userRoleInfoVOS = userDao.findRoleByOrgIds(pd);
            List<UserReviewInfoVO> userReviewInfoVOS = userDao.findReviewByOrgIds(pd);
            Map<String, List<UserRoleInfoVO>> roleMap = userRoleInfoVOS.stream().collect(Collectors.groupingBy(UserRoleInfoVO::getUserOrgId));
            Map<String, List<UserReviewInfoVO>> reviewMap = userReviewInfoVOS.stream().collect(Collectors.groupingBy(UserReviewInfoVO::getUserOrgId));
            List<UserExcelBean> userExcelBeans = new ArrayList<>();

            roleMap.forEach((k, v) -> {
                UserRoleInfoVO roleInfoVO = v.get(0);
                UserExcelBean userExcelBean = UserExcelBean.builder().userName(roleInfoVO.getUserName()).name(roleInfoVO.getName())
                        .orgName(roleInfoVO.getOrgName()).createTime(roleInfoVO.getCreateTime())
                        .roleCodes(v.stream().filter(userRoleInfoVO -> StringUtil.isNotBlank(userRoleInfoVO.getRoleCode()))
                        .map(UserRoleInfoVO::getRoleCode).collect(Collectors.joining(","))).build();
                if (reviewMap.containsKey(k)){
                    userExcelBean.setReviewCodes(reviewMap.get(k).stream().filter(userReviewInfoVO -> StringUtil.isNotBlank(userReviewInfoVO.getReviewCode()))
                            .map(UserReviewInfoVO::getReviewCode).collect(Collectors.joining(",")));
                }
                userExcelBeans.add(userExcelBean);
            });

//            DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//            //list 集合倒叙排序
//            userExcelBeans.sort((a1, a2) -> {
//                try {
//                    return df.parse(sdf.format(a2.getCreateTime())).compareTo(df.parse(sdf.format(a1.getCreateTime())));
//                } catch (Exception e) {
//                    log.error(ExceptionUtils.getFullStackTrace(e));
//                }
//                return 1;
//            });
            userExcelBeans.sort((a1, a2) -> a1.getUserName().compareTo(a2.getUserName()));

            String key = System.currentTimeMillis() + "-" + UUID.randomUUID().toString().replace("-", "");
            String fileName = key + ".xlsx";
            String exportPath = environment.getProperty("excel.path");
            LOGGER.info("UserService exportImportFile--exportPath--->"  + exportPath);
            /**
             * 导出路径不存在则创建
             */
            File file = new File(exportPath);
            if (!file.exists()) {
                file.mkdirs();
            }
            InputStream inputStream = this.getClass().getResourceAsStream("/exceldemo/user.xlsx");
            ExcelWriter excelWriter = EasyExcel.write(exportPath + fileName).withTemplate(inputStream).build();
            FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
            WriteSheet writeSheet = EasyExcel.writerSheet(0).build();
            excelWriter.fill(new FillWrapper("user", userExcelBeans), fillConfig, writeSheet);
            excelWriter.finish();
            PageData org = orgzationDao.findbyid(TokenUtil.getTokenOrgId());

            String excelName = org.getString("orgName") + "用户账号信息";
            redisUtils.set(key, excelName, 10 * 60);
            objResult = new ObjResult(CommonCode.SUCCESS);
            PageData pageData = new PageData();
            pageData.put("key", key);
            objResult.setPageData(pageData);
            return objResult;
        }catch (Exception e){
            objResult = new ObjResult(CommonCode.ERROR);
            LOGGER.error(ExceptionUtils.getMessage(e));
        }
        return objResult;

    }

    public String getNameById(String id){
        if (StringUtil.isBlank(id)){
            return null;
        }
        try {
            PageData user = userDao.findbyid(id);
            if(user != null){
                return user.getString("name");
            }
        }catch (Exception e){
            LOGGER.error(ExceptionUtils.getMessage(e));
        }
        return null;
    }

    /**
     * 返回致远URL
     * @return
     */
    public ObjResult getZhiyuanUrl(){
        ObjResult objResult=new ObjResult(CommonCode.SUCCESS);
        try{
            Environment environment = SpringUtil.getBean(Environment.class);
            String url = environment.getProperty("Zhiyuan.url");
            String password = environment.getProperty("Zhiyuan.password");
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("account","test1");
            jsonObject.put("timestamp",System.currentTimeMillis());
            PageData pageData=new PageData();
            pageData.put("url",url+AESUtils.encrypt(jsonObject.toJSONString(), password));
            objResult.setPageData(pageData);
        }catch (Exception e){
            e.printStackTrace();
            objResult = new ObjResult(CommonCode.ERROR);
            LOGGER.error(ExceptionUtils.getMessage(e));
        }
        return  objResult;
    }


    public void encryptBase64Data(){
        try {
            List<PageData> userList = userDao.listAll(null);
            List<PageData> updateList = new ArrayList<>();
            for (PageData user : userList){
                if (StringUtil.isNotBlank(user.getString("phone"))){
                    user.put("phone", EncryptUtil.encryptBase64(user.getString("phone"), BaseConstant.BASE64_KEY));
                    updateList.add(user);
                }
            }
            if (CollectionUtil.isNotEmpty(updateList)){
                for (PageData updateUser : updateList){
                    userDao.editPhone(updateUser);
                }
            }

        }catch (Exception e){
            LOGGER.error(ExceptionUtils.getStackTrace(e));
        }

    }


    public ObjResult editStatus(PageData p) {
        ObjResult objResult;
        try {
            String id = p.getString("id");
            Integer newStatus = p.getInteger("status");
            if (null == newStatus) return new ObjResult("状态不能为空");
            if (null == id) return new ObjResult("id不能为空");

            PageData p_user = userDao.findbyid(id);
            Integer oldStatus = p_user.getInteger("status");
            if(newStatus.equals(oldStatus)) return new ObjResult("状态未改变");

            p.put("updateTime", DateUtil.now());
            userDao.editStatus(p);

            UserCache.update(p.getString("id"));
            objResult = new ObjResult(CommonCode.SUCCESS);
        } catch (Exception e) {
            LOGGER.error(ExceptionUtils.getStackTrace(e));
            objResult = new ObjResult(CommonCode.ERROR);
            return objResult;
        }
        return objResult;
    }
}
